﻿using System;
using Assist;
using Autodesk.Revit.ApplicationServices;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using YArchitech.Revit;

namespace YArchitech.HVAC
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]
	internal class CmdPressKeys : IExternalCommand
	{
		private static WallType GetFirstWallTypeNamed(Document doc, string name)
		{
			FilterableValueProvider filterableValueProvider = new ParameterValueProvider(new ElementId(-1002001));
			FilterStringRuleEvaluator filterStringRuleEvaluator = new FilterStringEquals();
			ElementParameterFilter elementParameterFilter = new ElementParameterFilter(new FilterStringRule(filterableValueProvider, filterStringRuleEvaluator, name, false));
			return new FilteredElementCollector(doc).OfClass(typeof(WallType)).WherePasses(elementParameterFilter).FirstElement() as WallType;
		}

		private static Wall GetFirstWallUsingType(Document doc, WallType wallType)
		{
			FilterableValueProvider filterableValueProvider = new ParameterValueProvider(new ElementId(-1002050));
			FilterNumericRuleEvaluator filterNumericRuleEvaluator = new FilterNumericEquals();
			ElementParameterFilter elementParameterFilter = new ElementParameterFilter(new FilterElementIdRule(filterableValueProvider, filterNumericRuleEvaluator, wallType.Id));
			return new FilteredElementCollector(doc).OfClass(typeof(Wall)).WherePasses(elementParameterFilter).FirstElement() as Wall;
		}

		public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
		{
			UIApplication application = commandData.Application;
			UIDocument activeUIDocument = application.ActiveUIDocument;
			Application application2 = application.Application;
			Document document = activeUIDocument.Document;
			string name = "Generic - 203";
			WallType firstWallTypeNamed = CmdPressKeys.GetFirstWallTypeNamed(document, name);
			Wall firstWallUsingType = CmdPressKeys.GetFirstWallUsingType(document, firstWallTypeNamed);
			RevitVersionFuncs.AddToSelection(activeUIDocument.Selection, firstWallUsingType);
			if (activeUIDocument.Selection.GetElementIds().Count == 0)
			{
				Level level = new FilteredElementCollector(document).OfClass(typeof(Level)).FirstElement() as Level;
				Line curve = document.CreatYJKLine(XYZ.Zero, new XYZ(2.0, 0.0, 0.0), true);
				Transaction transaction = new Transaction(document, "Create dummy wall");
				transaction.Start();
				Wall element = document.CreatHYWall(curve, firstWallTypeNamed, level, 1.0, 0.0, false, false);
				transaction.Commit();
				RevitVersionFuncs.AddToSelection(activeUIDocument.Selection, element);
				Press.Keys("CS");
				RevitVersionFuncs.AddToSelection(activeUIDocument.Selection, element);
				Press.Keys("DE");
				Press.Keys("WA");
			}
			else
			{
				Press.Keys("CS");
			}
			return Autodesk.Revit.UI.Result.Succeeded;
		}
	}
}
